<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件

/**
 * [timezreo 返回当前日零点的时间戳]
 * @return [int] [时间戳]
 */
function timezreo() {
	return strtotime(date('Y-m-d', time()));
}

/**
 * @param $data 数据数组
 * @param $Separator 分割符
 */
function RecordsFile($data = array(), $Separator = "|") {
	$dir = 'log/';
	$filename = 'log';
	if (!$dir || !$filename || !is_array($data)) {
		return false;
	}

	if (!is_dir($dir)) {
		mkdir($dir);
	}

	$content = implode($Separator, $data);
	$result = file_put_contents($dir . '/' . $filename, (date('Y-m-d h:i:s', time())) . ' ' . $content . "\r\n", FILE_APPEND | LOCK_EX);
	return $result;
}

function getValueByKey($arr, $key) {
	$list = [];
	foreach ($arr as $value) {
		if (!empty($value[$key])) {
			$list[] = (int) $value[$key];
		}

	}
	return $list;
}

/**
 * 访问外部链接
 * @return [type] [description]
 */
    function getApi($url)
    {
        $result = file_get_contents($url);
		$arr = json_decode($result,true);
		return $arr;
	}

/**
 * 访问外部链接
 * @return [type] [description]
 */
    function getApiContent($arr,$type=0,$num=0)
    {
        //$result = file_get_contents($url);
        // var_dump($result);die;
        $futures  	   = M('futures')->select();															// 获取期货表数据
		// $this->futures = $futures;
		// $strp     	   = substr($result,strpos($result,'{')-1);
		// $arr      	   = json_decode($strp,true);
		//$arr      	   = json_decode($result,true);

		$array	  	   = array();
		$n  	  	   = 0;
		if (!$type || !$num) 
		{
			return $arr;
		}
		foreach ($arr as $k => $value) 
		{
			$suffix 	  = substr($k, -$num);
			$futuresName  = substr($k,0, -$num);
			if($suffix==$type)
			{
				$array[$futuresName] = $arr[$k];
			}
			foreach($futures as $val)
			{																					// 根据后台调控价处理获取过来的数据
				if($val['futures_name'] == $futuresName)
				{
					$array[$futuresName]['lastTrimed'] = $array[$futuresName]['last']+$val['futures_trim'];
					$array[$futuresName]['high'] += $val['futures_trim'];
					$array[$futuresName]['low']  += $val['futures_trim'];
					if($type=='qc')
					{
						$array[$futuresName]['increase'] = ($array[$futuresName]['last']-$val['futures_close_price'])/$val[
							'futures_close_price']*100;
					}
					
				}
			}
		}
		return $array;
    }

/**
 * 文件上传
 * @return [type] [description]
 */
function fileUpload($folder,$file)
{
	$uploads 			= new \Think\Upload(); 					// 实例化上传类
	$uploads->maxSize 	= 3145728; 								// 设置附件上传大小
	$uploads->exts 		= array('jpg', 'gif', 'png', 'jpeg'); 	// 设置附件上传类型
	$uploads->savePath 	= "$folder"; 							// 设置附件上传目录

	// 上传文件
	$info = $uploads->uploadOne($file);

	// 上传错误提示错误信息
	if (!$info) 
	{
		$this->error($uploads->getError());
	} 

	return $info;
}

/**
 * 邮件发送
 * @return [type] [description]
 */
function think_send_mail($to, $name, $subject = '', $body = '', $attachment = null)
{
	$config = C('THINK_EMAIL');
	vendor('PHPMailer.class#phpmailer'); //从PHPMailer目录导class.phpmailer.php类文件
	vendor('SMTP');
	$mail = new \PHPMailer(); //PHPMailer对象
	$mail->CharSet = 'UTF-8'; //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
	$mail->IsSMTP(); // 设定使用SMTP服务
	$mail->SMTPDebug = 0; // 关闭SMTP调试功能
	// 1 = errors and messages
	// 2 = messages only
	$mail->SMTPAuth = true; // 启用 SMTP 验证功能
	$mail->SMTPSecure = 'ssl'; // 使用安全协议
	$mail->Host = $config['SMTP_HOST']; // SMTP 服务器
	$mail->Port = $config['SMTP_PORT']; // SMTP服务器的端口号
	$mail->Username = $config['SMTP_USER']; // SMTP服务器用户名
	$mail->Password = $config['SMTP_PASS']; // SMTP服务器密码
	$mail->SetFrom($config['FROM_EMAIL'], $config['FROM_NAME']);
	$replyEmail = $config['REPLY_EMAIL']?$config['REPLY_EMAIL']:$config['FROM_EMAIL'];
	$replyName = $config['REPLY_NAME']?$config['REPLY_NAME']:$config['FROM_NAME'];
	$mail->AddReplyTo($replyEmail, $replyName);
	$mail->Subject = $subject;
	$mail->AltBody = "为了查看该邮件，请切换到支持 HTML 的邮件客户端";
	$mail->MsgHTML($body);
	$mail->AddAddress($to, $name);
	if(is_array($attachment))
	{   // 添加附件
		foreach ($attachment as $file)
		{
			is_file($file) && $mail->AddAttachment($file);
		}
	}
	return $mail->Send() ? true : $mail->ErrorInfo;
}

/**
 * 图片上传
 * @return [type] [description]
 */
function imgUpload($img,$folder_name)
{
	$path  = './Public/upload/'.$folder_name;
	$dir = iconv("UTF-8", "GBK", $path);
    if (!is_dir($dir))
    {
        mkdir($dir,0777,true);
    } 
	if(is_array($img))
	{
		foreach ($img as $key => $value) 
		{
			// var_dump($value);die;
			//获取图片的base64码,处理
			list($ext,$img_base) = explode(',',$value);
			// var_dump(base64_decode($img_base));die;
			//获取扩展名
			$ext1 = explode(';',$ext);
			$ext2 = explode('/',$ext1[0]);
			$ext  = $ext2[1];
			//保存图片
			$img_name = time().rand(100,999).'.'.$ext;
			$out_file = $dir.'/'.$img_name;
			$res = file_put_contents($out_file,base64_decode($img_base));
			if($res == 0){
				return false;
			}
			$file = substr($out_file,1);
			$arr[$key] = $file;
		}
		$arr = implode(';',$arr);
	}
	else
	{
		list($ext,$img_base) = explode(',',$img);
			//获取扩展名
			$ext1 = explode(';',$ext);
			$ext2 = explode('/',$ext1[0]);
			$ext  = $ext2[1];
			//保存图片
			$img_name = time().rand(100,999).'.'.$ext;
			$out_file = $path.'/'.$img_name;

			$res = file_put_contents($out_file,base64_decode($img_base));

			if($res == 0){
				return false;
			}
			$file = substr($out_file,1);
			$arr = $file;
	}
	return $arr;
}

/**
     * 失败
     * @return [type] [description]
     */
    function json_error($msg='失败')
    {
        //插入日志
        // $this->intoLog(2, $msg);
        // return json_encode(['code'=>400, 'msg'=>$msg]);
        return json(['code'=>400, 'msg'=>$msg]);
    }

    /**
     * 成功
     * @return [type] [description]
     */
    function json_success($data=[], $msg='成功')
    {
        if (is_string($data)) {
            $msg  = $data;
            $data = [];
        }
        // $this->intoLog(1);
        //插入日志
        // return json_encode(['code'=>200, 'data'=>$data, 'msg'=>$msg]);
        return json(['code'=>200, 'data'=>$data, 'msg'=>$msg]);
  
    }

    // 生成邀请码
    function code_num() {
		$code_num = mt_rand(100000, 999999);
		$count = db('user')->where(['user_reg_code' => $code_num])->count();	// 检查是否重复

		if ($count) {
			return code_num();
		} else {
			return $code_num;
		}
	}

	function yzm($phone,$type='zc') 
	{
		if(empty($phone))
		{
			return json_error('手机号不能为空！');
		}

		if(strlen($phone) == "11") 
		{ 

			if(preg_match("/^1[345789]\d{9}$/", $phone))
			{
				// 判断重复请求
				$prevCode = db('phone_code')->where(['user_phone' => $phone])->order('mes_id desc')->find();
				if ($prevCode) 
				{
					# 如果有记录
					$prevTime = explode(',',$prevCode['phone_code'])[1];
					if($prevCode && time()-$prevTime<60)
					{
						return json_error('60秒内只能发送一次');
					}
				}
				
				$smsnum 	= mt_rand(100000, 999999);
				$phpCode 	= db('phone_code');
				$data['phone_code'] = $smsnum . $type . ',' . time();
				$data['user_phone'] = $phone;
				$num = $phpCode->insert($data);
				if($num)
				{
					if ($phone) 
					{
						$mes = sendSms($phone, $smsnum);
					}
					return json_success(['code'=>$smsnum],'验证码发送成功');
				}
				else
				{
					return json_error('验证码发送失败');
				}
			}
			else
			{
				return json_error('手机号匹配不到！');
			}
		}
		else
		{ 
			return json_error('请填写11位有效手机号！');
		} 
	}

	//发送短信
	function sendSms($mobiles,$smsnum)
	{
	    $mobiles  = trim($mobiles);
	    $content  = urlencode(iconv( "UTF-8", "gb2312//IGNORE" , trim("验证码为".$smsnum.",有效期为5分钟!【西红柿】")));
	    $username = 'guojin';
	    $password = 'guojin123';
	    $fp       = Fopen("http://120.25.66.83:9877/api/send.aspx?username=$username&password=$password&mobiles=$mobiles&content=$content","r");
	    $ret      = fgetss($fp,255);
	    $str      = urldecode($ret);
	    Fclose($fp);
	    return $str;
	}



    

